<template>
  <div class="file-explorer-button">
    <ElButton size="mini" :disabled="disabled || !selectedRows.length" icon="fa fa-trash-o" @click="deleteFile()">
      删除
    </ElButton>
  </div>
</template>

<script>
  export default {
    name: 'DeleteFileButton',
    inject: ['explorer'],
    props: {
      disabled: Boolean,
      api: Function,
      selectedRows: {
        type: Array,
        default: () => []
      }
    },
    methods: {
      async deleteFile(rows) {
        const selectedRows = rows || this.selectedRows
        if (!selectedRows.length) {
          this.$message.warning('请选择要删除的文件！')
          return
        }
        await this.$confirm(
          `你确定要删除选中的[<span class="break-word" style="color: orange">${selectedRows.length}</span>]个文件吗？`,
          '系统提示',
          {
            type: 'warning',
            modal: true,
            dangerouslyUseHTMLString: true,
            iconClass: 'el-icon-question',
            closeOnClickModal: false,
            confirmButtonClass: 'el-button--danger',
            cancelButtonClass: 'el-button',
            beforeClose: async (action, instance, done) => {
              if (action === 'confirm') {
                try {
                  instance.confirmButtonLoading = true
                  instance.confirmButtonText = '删除...'
                  const fileIds = selectedRows.map(value => value.id)
                  if (fileIds.length !== 0) {
                    await this.doDeleteFile(fileIds)
                    await this.updateTree(fileIds)
                  }
                  done()
                } catch (_) {
                  // console.log(_)
                }
                instance.confirmButtonLoading = false
                instance.confirmButtonText = '确定'
              } else {
                done()
              }
            }
          }
        ).catch(_ => _)
      },
      async updateTree(folderIds) {
        const { explorer } = this
        folderIds.forEach(folderId => {
          if (explorer.$refs.tree) {
            const nodes = explorer.$refs.tree.$refs.etTree.findTreeNode(folderId)
            nodes.forEach(node => {
              explorer.$refs.tree.$refs.etTree.$refs.tree.remove(node.data)
            })
          }
        })
        await explorer.reload()
      },
      async doDeleteFile(fileIds) {
        const res = await this.api(fileIds)
        if (res.data.code === 0) {
          this.$message.success('删除成功!')
          await this.explorer.reload()
        } else {
          this.$message.error(res.message)
        }
      }
    }
  }
</script>
